/*
 * Copyright 2022 NAVER Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.navercorp.pinpoint.plugin.kotlinx.coroutines.interceptor;

import com.navercorp.pinpoint.bootstrap.async.AsyncContextAccessor;
import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig;
import com.navercorp.pinpoint.bootstrap.context.AsyncContext;
import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
import com.navercorp.pinpoint.bootstrap.context.TraceContext;
import com.navercorp.pinpoint.bootstrap.interceptor.AsyncContextSpanEventSimpleAroundInterceptor;
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.plugin.kotlinx.coroutines.CoroutinesConfig;
import com.navercorp.pinpoint.plugin.kotlinx.coroutines.CoroutinesConstants;
import kotlin.coroutines.Continuation;
import kotlin.coroutines.CoroutineContext;

/**
 * @author Taejin Koo
 */
public class ResumeWithInterceptor extends AsyncContextSpanEventSimpleAroundInterceptor {

    private final ServiceType serviceType;

    private final boolean recordThreadName;

    public ResumeWithInterceptor(TraceContext traceContext, MethodDescriptor descriptor, ServiceType serviceType) {
        super(traceContext, descriptor);
        this.serviceType = serviceType;

        ProfilerConfig profilerConfig = traceContext.getProfilerConfig();
        this.recordThreadName = new CoroutinesConfig(profilerConfig).isRecordThreadName();
    }

    public ResumeWithInterceptor(TraceContext traceContext, MethodDescriptor methodDescriptor) {
        this(traceContext, methodDescriptor, ServiceType.INTERNAL_METHOD);
    }

    @Override
    protected AsyncContext getAsyncContext(Object target, Object[] args, Object result, Throwable throwable) {
        return getAsyncContext(target);
    }

    @Override
    protected AsyncContext getAsyncContext(Object target, Object[] args) {
        return getAsyncContext(target);
    }

    private AsyncContext getAsyncContext(Object object) {
        if (object instanceof Continuation) {
            CoroutineContext context = ((Continuation<?>) object).getContext();
            if (context instanceof AsyncContextAccessor) {
                AsyncContextAccessor accessor = (AsyncContextAccessor) context;
                AsyncContext asyncContext = accessor._$PINPOINT$_getAsyncContext();

                return asyncContext;
            }
        }
        return null;
    }


    @Override
    protected void doInBeforeTrace(SpanEventRecorder recorder, AsyncContext asyncContext, Object target, Object[] args) {
        recorder.recordServiceType(serviceType);
    }

    @Override
    protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
        recorder.recordApi(methodDescriptor);
        recorder.recordException(throwable);

        if (recordThreadName) {
            Thread currentThread = Thread.currentThread();
            if (currentThread != null) {
                String threadName = currentThread.getName();
                if (threadName != null) {
                    recorder.recordAttribute(CoroutinesConstants.COROUTINE_THREAD_NAME_ANNOTATION_KEY, threadName);
                }
            }
        }
    }
}
